package com.fangda.network.tcp.client;

import com.fangda.network.NetworkConfig;
import com.fangda.network.NetworkMessage;
import com.fangda.network.NetworkMessageCallback;
import com.fangda.network.NetworkType;
import com.fangda.network.tcp.AbstractTcpNetwork;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.net.NetClient;
import io.vertx.core.net.NetSocket;
import lombok.Getter;
import lombok.Setter;

public class TcpClientNetwork extends AbstractTcpNetwork {

    /**
	 *
	 */
	private static final long serialVersionUID = 6212359518712806181L;

	@Setter
    @Getter
    protected NetClient client;

    @Setter
    @Getter
    private NetSocket socket;

    public TcpClientNetwork(String id, NetworkConfig config) {
        super(id, config);
    }

    @Override
    public NetworkType getNetworkType() {
        return NetworkType.TCP_CLIENT;
    }

    @Override
    public void shutdown() {
        if(socket != null) {
            socket.close(r -> {
                setAlive(!r.succeeded());
                if(callback != null) {
                    callback.connectionChange(false, null);
                }
            });
        } else {
            setAlive(false);
        }
    }

    @Override
    public void reload() {
        shutdown();
        connect();
    }

    public void connect() {
        client.connect(config.getPort(), config.getIp(), result -> {
            if(result.succeeded()) {
                socket = result.result();
                alive = true;
                initSocket(socket, null);
            } else {
                alive = false;
            }
            if(callback != null) {
                callback.connectionChange(result.succeeded(), result.cause());
            }
        });
    }

    public void send(NetworkMessage message, NetworkMessageCallback messageCallback) {
        socket.write(Buffer.buffer(message.getPayload()), res -> {
            if(messageCallback != null) {
                messageCallback.callback(res, socket.remoteAddress());
            }
        });
    }


}
